package com.coai.message.controller

import com.coai.message.dto.SendMessageRequest
import com.coai.message.dto.TypingNotification
import com.coai.message.service.MessageService
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.annotation.Payload
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.stereotype.Controller
import java.security.Principal

@Controller
class WebSocketMessageController(
    private val messageService: MessageService,
    private val messagingTemplate: SimpMessagingTemplate
) {
    
    /**
     * 处理客户端发送的消息
     */
    @MessageMapping("/message.send")
    fun sendMessage(
        @Payload request: SendMessageRequest,
        principal: Principal
    ) {
        val message = messageService.sendMessage(request, principal.name)
        // 消息已在service层推送，这里不需要额外处理
    }
    
    /**
     * 处理正在输入通知
     */
    @MessageMapping("/typing")
    fun handleTyping(
        @Payload notification: TypingNotification,
        principal: Principal
    ) {
        // 广播到会话的所有参与者
        messagingTemplate.convertAndSend(
            "/topic/conversation/${notification.conversationId}/typing",
            notification.copy(userId = principal.name)
        )
    }
    
    /**
     * 处理在线状态
     */
    @MessageMapping("/status.update")
    fun updateStatus(
        @Payload status: String,
        principal: Principal
    ) {
        // 广播用户状态更新
        messagingTemplate.convertAndSend(
            "/topic/user.status",
            mapOf(
                "userId" to principal.name,
                "status" to status,
                "timestamp" to System.currentTimeMillis()
            )
        )
    }
}
